#!/bin/bash

set -e

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
source "${ROOT}/script/lib/ui.sh"

usage() {
  cat <<USAGE >&2
usage: $0 [-h|--help] <command>

COMMANDS:
  compile       Compile the dashboard assets

  run           Build and run the dashboard

OPTIONS:
  -h, --help    Show this message
USAGE
}

main() {
  if [[ "$1" = "-h" ]] || [[ "$1" = "--help" ]]; then
    usage
    exit
  fi

  case "$1" in
    compile)
      compile
      ;;
    run)
      run
      ;;
    *)
      usage
      exit 1
      ;;
  esac
}

compile() {
  local flynn_host="${ROOT}/build/bin/flynn-host"
  local builder_image="${ROOT}/build/image/dashboard-compiled.json"

  # compile the dashboard in place
  "${flynn_host}" run \
    --bind    "${ROOT}:${ROOT},${ROOT}/dashboard/app:/app" \
    --limits  "temp_disk=1G" \
    --workdir "${ROOT}" \
    "${builder_image}" \
    sh dashboard/img/compile.sh
}

run() {
  cd "${ROOT}/dashboard"

  info "building dashboard server"
  go build

  info "setting environment variables"
  export DISABLE_CACHE="true"
  export LOGIN_TOKEN="test"
  export SESSION_SECRET="abc123"
  export URL="http://dashboard.1.localflynn.com:4457"
  export PORT="4457"
  export APP_NAME="dashboard"
  export DEFAULT_ROUTE_DOMAIN="1.localflynn.com"
  export CONTROLLER_DOMAIN="controller.1.localflynn.com"
  export CONTROLLER_KEY="${CONTROLLER_KEY}"
  export GITHUB_TOKEN="MY_TOKEN"

  info "running dashboard on ${URL} (TOKEN='${LOGIN_TOKEN}')"
  ./dashboard
}

main $@
